﻿using System;
using System.Collections.Generic;
using System.Linq;
using Algoritmia.Utils;

namespace Algoritmia.DataStructures.Sets
{
    public class ListSet<T> : ISet<T>
    {
        private Lists.IList<T> _list;
        private readonly Func<Lists.IList<T>> _createList;

        public ListSet(IEnumerable<T> items= null, Func<Lists.IList<T>> createList=null)
        {
            items = items ?? Enumerable.Empty<T>();
            createList = createList ?? (() => AlgoritmiaFactory.Lists<T>.Default);
            _list = createList();
            _createList = createList;
            foreach (var item in items)
            {
                Add(item);
            }
        }

        #region ISet<T> Members

        public bool Contains(T elem)
        {
            return _list.Contains(elem);
        }

        public void Add(T elem)
        {
            if (!_list.Contains(elem))
                _list.Add(elem);
        }

        public void AddUnchecked(T elem)
        {
            
            _list.Add(elem);
        }

        public void Discard(T elem)
        {
            _list.Remove(elem);
        }

        public bool Remove(T elem)
        {
            return _list.Remove(elem);
        }

        public void Clear()
        {
            _list = _createList();
        }

        #endregion

        #region IEnumerable<T> Members

        public IEnumerator<T> GetEnumerator()
        {
            return _list.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _list.GetEnumerator();
        }

        #endregion

        #region IEquatable<ISet<T>> Members

        public bool Equals(ISet<T> other)
        {
            return Count == other.Count && this.IsSuperSetOf(other);
        }

        #endregion

        #region ICountable Members

        public int Count
        {
            get { return _list.Count; }
        }

        #endregion

        public override string ToString()
        {
            return String.Format("{0} <{1}> {{{2}}}", GetType().Name, typeof(T).Name, string.Join(", ", this));
        }
    }
}
